package com.jarchie.androiddev.http

import com.google.gson.Gson
import okhttp3.ResponseBody
import org.json.JSONObject
import retrofit2.Converter
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type

class GsonResponseBodyConverter<T>(private val gson: Gson, private val type: Type) :
    Converter<ResponseBody, ApiResult<T>> {
    override fun convert(value: ResponseBody): ApiResult<T>? {
        value.use {
            if (type !is ParameterizedType || !ApiResult::class.java.isAssignableFrom((type.rawType) as Class<*>))
                throw java.lang.RuntimeException("返回类型必须是ApiResult类型")
            val apiResult = ApiResult<T>()
            val response = JSONObject(value.string())
            apiResult.code = response.optInt("code")
            apiResult.msg = response.optString("msg")
            val data: JSONObject? = response.optJSONObject("data")
            if (data != null) {
                val argumentType = type.actualTypeArguments[0]
                apiResult.body = gson.fromJson(data.toString(), argumentType)
            }
            return apiResult
        }
    }
}